package com.fer.tankr.models.enemies;

import org.andengine.extension.physics.box2d.PhysicsWorld;
import org.andengine.opengl.texture.region.ITextureRegion;
import org.andengine.opengl.vbo.VertexBufferObjectManager;

import com.badlogic.gdx.math.Vector2;
import com.fer.andenginemvc.api.gameObjects.GameObject;

public class BoxFuckerEnemy extends Enemy {

	private GameObject<?> toFollow;
	private boolean stateSleeping;
	private boolean stateChange;
	
	private ITextureRegion textureSleeping;
	private ITextureRegion textureActive;
	
	public BoxFuckerEnemy(PhysicsWorld world, VertexBufferObjectManager vbom,
			float x, float y, GameObject<?> toFollow, ITextureRegion textureSleeping, ITextureRegion textureActive) {
		super(world, vbom, x, y, 25, 25, 4);
		this.toFollow = toFollow;
		stateSleeping = true;
		stateChange = false;
		attachSprite(textureSleeping, x, y);
		
		this.textureActive = textureActive;
		this.textureSleeping = textureSleeping;
	}

	@Override
	public void onUpdate(float pSecondsElapsed) {
		float x = toFollow.entity.getX();
		float y = toFollow.entity.getY();
		float width = this.entity.getWidth();
		float height = this.entity.getHeight();
		
		double distance = Math.sqrt(Math.pow(entity.getX()-x,2) + Math.pow(entity.getY()-y,2));
		boolean near = distance <2.5*(width+height);
		if ((near && stateSleeping) || (!near && !stateSleeping))
		{
			stateChange = true;
		}
		else
		{
			stateChange = false;
		}
		if (near)
		{
			stateSleeping = false;
			move();
		}
		else
		{
			stateSleeping = true;
			body.setLinearVelocity(0, 0);
		}
		
		if (stateChange)
		{
			if (!stateSleeping)
			{
				entity.detachChildren();
				attachSprite(textureActive, 0, 0);
			}
			else
			{
				entity.detachChildren();
				attachSprite(textureSleeping, 0, 0);
			}
		}
	}

	private void move() {
		float x = toFollow.entity.getX()-entity.getX();
		float y = toFollow.entity.getY()-entity.getY();
		Vector2 v = new Vector2(x, y).nor().mul(3.5f);
		body.setLinearVelocity(v);
		
	}

}
